package net.nagaseyasuhito.nicola.page;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.NoResultException;

import net.nagaseyasuhito.nicola.NicolaSession;
import net.nagaseyasuhito.nicola.component.CurrentEntryPanel;
import net.nagaseyasuhito.nicola.component.EntriesTab;
import net.nagaseyasuhito.nicola.component.EntriesWithFriendsTab;
import net.nagaseyasuhito.nicola.component.ReplyEntriesTab;
import net.nagaseyasuhito.nicola.component.FriendsPanel;
import net.nagaseyasuhito.nicola.entity.User;
import net.nagaseyasuhito.nicola.service.UserService;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.tabs.AjaxTabbedPanel;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.StringResourceModel;

import com.google.inject.Inject;

public class UserPage extends BasePage {
	private static final long serialVersionUID = 1L;

	@Inject
	private UserService userService;

	public UserPage(PageParameters pageParameters) {
		final User user;

		//	存在しないユーザーだった場合IndexPageにredirect
		try {
			user = this.userService.findByName(pageParameters.getString("name"));
		}
		catch(NoResultException e) {
			this.setResponsePage(IndexPage.class);
			this.setRedirect(true);
			return ;
		}

		//	ユーザーが自分自身だった場合HomePageにredirect
		if(NicolaSession.get().isSignedIn() && NicolaSession.get().getUser().equals(user)) {
			this.setResponsePage(MyPage.class);
			this.setRedirect(true);
			return ;
		}

		this.add(new CurrentEntryPanel("entry", user));
		this.add(new FriendsPanel("friends", user));
		
		List<AbstractTab> tabs = new ArrayList<AbstractTab>();
		tabs.add(new EntriesWithFriendsTab(user, 10));
		tabs.add(new EntriesTab(user, 10));
		tabs.add(new ReplyEntriesTab(user, 10));
		this.add(new AjaxTabbedPanel("entries", tabs));

		this.add(new AjaxLink("follow") {
			private static final long serialVersionUID = 1L;

			@Inject
			private UserService userService;

			@Override
			public void onClick(AjaxRequestTarget target) {
				if(this.userService.contains(NicolaSession.get().getUser(), user)) {
					this.userService.unfollow(NicolaSession.get().getUser(), user);
				}
				else {
					this.userService.follow(NicolaSession.get().getUser(), user);
				}

				target.addComponent(this);
			}

			@Override
			protected void onBeforeRender() {
				if(this.userService.contains(NicolaSession.get().getUser(), user)) {
					this.get("action").setModel(new StringResourceModel("unfollow", null, null));
				}
				else {
					this.get("action").setModel(new StringResourceModel("follow", null, null));
				}
				super.onBeforeRender();
			}
		}.add(new Label("action")).setVisible(NicolaSession.get().isSignedIn()));
	}
}
